<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {
    
    private $data = array();

    public function  __construct() {
        parent::__construct();
        //Load Helper
        $this->load->helper("url");
        $this->data['base_url'] = base_url();
        $this->data['root_url'] = $this->config->item('root_url');
        $this->data['is_mobile'] = $this->agent->is_mobile();
        $this->load->library('pagination'); 
        $this->config->set_item('compress_output', TRUE);
        
         //Load Libary
        $this->load->library("ci_smarty");

        //$this->output->enable_profiler(TRUE);
        
        // Load Model
        $this->load->Model("Mcategory");
        $this->load->Model("Minfo");
        $this->load->Model("Mbook");
        $this->load->Model("MChapter");
        $this->load->Model("MPromotion");
        $this->load->Model("MSeo");

        if(WEB_TYPE == 'T'){
            $this->data['dataAll'] = $this->Mcategory->getCategoriesByType('T');
        }else {
            $this->data['dataAll'] = $this->Mcategory->getCategoriesByType('C');
        }

        //Load Data
        $this->data['infoAll'] = $this->Minfo->getInfo();
        $this->data['bookBestList'] = $this->Mbook->getBookPopularBySumViewChapter();
        $this->data['promotion1'] = $this->MPromotion->getPromotionByPos(1);
        $this->data['promotion2'] = $this->MPromotion->getPromotionByPos(2);
        $this->data['seoData'] = $this->MSeo->getCommonSEO();
    }

    public function index($curPage = 1)
    {
        $booksByRank = $this->Mbook->getBooksByRank();
        $this->data['listBooksByRank'] = $booksByRank;
        
        // config page
        $indexPageConfig['base_url']      = base_url("");
        $indexPageConfig['total_rows']    = $this->Mbook->countBook();
        $indexPageConfig['per_page']      = 30;
        $indexPageConfig['uri_segment']   = 1;
        $indexPageConfig['cur_page']      = $curPage;
        $indexPageConfig['suffix']        = '.html#danh-sach-truyen';

        $curOffset = $indexPageConfig['per_page'] * ($curPage - 1);

        $this->pagination->initialize($indexPageConfig);

        $this->data['pageList'] = $this->pagination->create_links();
        
        $booksAll = $this->Mbook->getBooksAll($indexPageConfig['per_page'], $curOffset);

        $booksAllFull = array();
        foreach ($booksAll as $book) {
            if ($book['use_volume'] == 'Y') {
                $book['lastChapter'] = $this->MChapter->getLastChapterByBookIdByVolume($book['id']);
            } else {
                $book['lastChapter'] = $this->MChapter->getLastChapterByBookId($book['id']);
            }
            $booksAllFull[] = $book;
        }

        $this->data['listBooksAll'] = $booksAllFull;

        $this->data['seoTemplate'] = $this->MSeo->getTemplateSEO($this->data['seoData']);

        $this->ci_smarty->view('frontend/index.tpl', $this->data);
    }

}